package com.changgou.seckill.service.impl;

import com.changgou.seckill.dao.SeckillGoodsMapper;
import com.changgou.seckill.dao.SeckillOrderMapper;
import com.changgou.seckill.pojo.SeckillGoods;
import com.changgou.seckill.pojo.SeckillOrder;
import com.changgou.seckill.pojo.SeckillStatus;
import com.changgou.seckill.service.SeckillOrderService;
import com.changgou.seckill.thread.MultiThreadingCreateOrder;
import com.changgou.utils.IdWorker;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;
import tk.mybatis.mapper.entity.Example;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.Future;

/****
 * @Author:shenkunlin
 * @Description:SeckillOrder业务层接口实现类
 * @Date 2019/6/14 0:16
 *****/
@Service
public class SeckillOrderServiceImpl implements SeckillOrderService {

    @Autowired
    private SeckillOrderMapper seckillOrderMapper;


    @Autowired
    private MultiThreadingCreateOrder multiThreadingCreateOrder;

    @Autowired
    private IdWorker idWorker;

    @Autowired
    private RedisTemplate redisTemplate;


    /****
     * 添加订单
     * @param id
     * @param time
     * @param username
     */
    @Override
    public Boolean add(Long id, String time, String username) throws ExecutionException, InterruptedException {

        Long UserQueueCount = redisTemplate.boundHashOps("UserQueueCount_" + username).increment(id, 1);//用户下单计时器
        if (UserQueueCount > 1) {
            throw new RuntimeException("妈的,秒杀别想着重复下单了老哥，先去付款吧！");

        }
        SeckillStatus seckillStatus = new SeckillStatus(username, new Date(), 1, id, time);

        redisTemplate.boundListOps("seckillQueue").leftPush(seckillStatus);
        //  redisTemplate.boundHashOps("UserQueueStatus"+username).put(seckillOrder.getId(), seckillStatus);


        //多线程
        Future<String> future = multiThreadingCreateOrder.createOrder();

        String s = null;

            s = future.get();


        if (s != null) {
            throw new RuntimeException(s);
        }
        return true;


    }

    //   全部订单   redis+mysql            未付款 redis         已付款的   mysql
    @Override
    public List<SeckillStatus> queryStatus(String username, String status) {
        List<SeckillStatus> seckillStatusList = new ArrayList<>();
        //全部订单
        if ("1".equals(status)) {
            seckillStatusList = redisTemplate.boundHashOps("UserQueueStatus_" + username).values();
            SeckillOrder order = new SeckillOrder();
            order.setUserId(username);
            List<SeckillOrder> seckillOrders = seckillOrderMapper.select(order);
            if (seckillOrders != null && seckillOrders.size() > 0) {
                for (SeckillOrder seckillOrder : seckillOrders) {
                    SeckillStatus seckillStatus = new SeckillStatus();
                    seckillStatus.setOrderId(seckillOrder.getId());//订单id
                    seckillStatus.setGoodsId(seckillOrder.getSeckillId());//秒杀id
                    seckillStatus.setMoney(Float.valueOf(seckillOrder.getMoney()));
                    seckillStatus.setUsername(seckillOrder.getUserId());//创建时间
                    seckillStatus.setCreateTime(seckillOrder.getCreateTime());
                    seckillStatus.setPayTime(seckillOrder.getPayTime());
                    seckillStatus.setStatus(Integer.valueOf(seckillOrder.getStatus()));//状态

                    seckillStatusList.add(seckillStatus);
                }
            }
        } else if ("0".equals(status)) {// 未付款
            seckillStatusList = redisTemplate.boundHashOps("UserQueueStatus_" + username).values();
        }


        return seckillStatusList;
    }

    /**
     * SeckillOrder条件+分页查询
     *
     * @param seckillOrder 查询条件
     * @param page         页码
     * @param size         页大小
     * @return 分页结果
     */
    @Override
    public PageInfo<SeckillOrder> findPage(SeckillOrder seckillOrder, int page, int size) {
        //分页
        PageHelper.startPage(page, size);
        //搜索条件构建
        Example example = createExample(seckillOrder);
        //执行搜索
        return new PageInfo<SeckillOrder>(seckillOrderMapper.selectByExample(example));
    }

    /**
     * SeckillOrder分页查询
     *
     * @param page
     * @param size
     * @return
     */
    @Override
    public PageInfo<SeckillOrder> findPage(int page, int size) {
        //静态分页
        PageHelper.startPage(page, size);
        //分页查询
        return new PageInfo<SeckillOrder>(seckillOrderMapper.selectAll());
    }

    /**
     * SeckillOrder条件查询
     *
     * @param seckillOrder
     * @return
     */
    @Override
    public List<SeckillOrder> findList(SeckillOrder seckillOrder) {
        //构建查询条件
        Example example = createExample(seckillOrder);
        //根据构建的条件查询数据
        return seckillOrderMapper.selectByExample(example);
    }


    /**
     * SeckillOrder构建查询对象
     *
     * @param seckillOrder
     * @return
     */
    public Example createExample(SeckillOrder seckillOrder) {
        Example example = new Example(SeckillOrder.class);
        Example.Criteria criteria = example.createCriteria();
        if (seckillOrder != null) {
            // 主键
            if (!StringUtils.isEmpty(seckillOrder.getId())) {
                criteria.andEqualTo("id", seckillOrder.getId());
            }
            // 秒杀商品ID
            if (!StringUtils.isEmpty(seckillOrder.getSeckillId())) {
                criteria.andEqualTo("seckillId", seckillOrder.getSeckillId());
            }
            // 支付金额
            if (!StringUtils.isEmpty(seckillOrder.getMoney())) {
                criteria.andEqualTo("money", seckillOrder.getMoney());
            }
            // 用户
            if (!StringUtils.isEmpty(seckillOrder.getUserId())) {
                criteria.andEqualTo("userId", seckillOrder.getUserId());
            }
            // 创建时间
            if (!StringUtils.isEmpty(seckillOrder.getCreateTime())) {
                criteria.andEqualTo("createTime", seckillOrder.getCreateTime());
            }
            // 支付时间
            if (!StringUtils.isEmpty(seckillOrder.getPayTime())) {
                criteria.andEqualTo("payTime", seckillOrder.getPayTime());
            }
            // 状态，0未支付，1已支付
            if (!StringUtils.isEmpty(seckillOrder.getStatus())) {
                criteria.andEqualTo("status", seckillOrder.getStatus());
            }
            // 收货人地址
            if (!StringUtils.isEmpty(seckillOrder.getReceiverAddress())) {
                criteria.andEqualTo("receiverAddress", seckillOrder.getReceiverAddress());
            }
            // 收货人电话
            if (!StringUtils.isEmpty(seckillOrder.getReceiverMobile())) {
                criteria.andEqualTo("receiverMobile", seckillOrder.getReceiverMobile());
            }
            // 收货人
            if (!StringUtils.isEmpty(seckillOrder.getReceiver())) {
                criteria.andEqualTo("receiver", seckillOrder.getReceiver());
            }
            // 交易流水
            if (!StringUtils.isEmpty(seckillOrder.getTransactionId())) {
                criteria.andEqualTo("transactionId", seckillOrder.getTransactionId());
            }
        }
        return example;
    }

    /**
     * 删除
     *
     * @param id
     */
    @Override
    public void delete(Long id) {
        seckillOrderMapper.deleteByPrimaryKey(id);
    }

    /**
     * 修改SeckillOrder
     *
     * @param seckillOrder
     */
    @Override
    public void update(SeckillOrder seckillOrder) {
        seckillOrderMapper.updateByPrimaryKey(seckillOrder);
    }

    /**
     * 增加SeckillOrder
     *
     * @param seckillOrder
     */
    @Override
    public void add(SeckillOrder seckillOrder) {
        seckillOrderMapper.insert(seckillOrder);
    }

    /**
     * 根据ID查询SeckillOrder
     *
     * @param id
     * @return
     */
    @Override
    public SeckillOrder findById(Long id) {
        return seckillOrderMapper.selectByPrimaryKey(id);
    }

    /**
     * 查询SeckillOrder全部数据
     *
     * @return
     */
    @Override
    public List<SeckillOrder> findAll() {
        return seckillOrderMapper.selectAll();
    }


    //更新订单状态
    @Override
    public void updateStatus(String out_trade_no, String user_id, String transaction_id, String time_end) throws ParseException {
        // SeckillStatus  seckillStatus= (SeckillStatus) redisTemplate.boundHashOps("UserQueueStatus_" + user_id).get(out_trade_no);

        //Long orderId = seckillStatus.getOrderId();
        // 获取订单
        SeckillOrder seckillOrder = (SeckillOrder) redisTemplate.boundHashOps("SeckillOrder_" + user_id).get(Long.valueOf(out_trade_no));
        // 设置订单的属性信息
        if (seckillOrder != null) {
            seckillOrder.setStatus("1");                    // 支付状态：支付成功
            seckillOrder.setTransactionId(transaction_id);  // 交易流水
            SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmss");
            Date payTime = sdf.parse(time_end);
            seckillOrder.setPayTime(payTime);               // 支付完成日期

            // 将订单持久化到数据库中
            seckillOrderMapper.insertSelective(seckillOrder);

            // 删除redis中的订单、删除排队信息、删除重复下单信息
            redisTemplate.boundHashOps("SeckillOrder_" + user_id).delete(out_trade_no);
            redisTemplate.boundHashOps("UserQueueStatus_" + user_id).delete(out_trade_no);
            redisTemplate.boundHashOps("UserQueueCount_" + user_id).delete(seckillOrder.getSeckillId());
        }


    }

    @Override
    public void deleteOrder(String out_trade_no, String user_id) {
        // 支付失败，删除订单并且回滚库存信息（商品信息、商品id队列、商品库存）
        // 获取订单
        SeckillOrder seckillOrder = (SeckillOrder) redisTemplate.boundHashOps("SeckillOrder_" + user_id).get(out_trade_no);
        // 排队信息
        SeckillStatus seckillStatus = (SeckillStatus) redisTemplate.boundHashOps("UserQueueStatus_" + user_id).get(out_trade_no);
        if (seckillOrder != null && seckillStatus != null) {
            // 1、删除订单
            redisTemplate.boundHashOps("SeckillOrder_" + user_id).delete(out_trade_no);

            // 2、回滚库存
            // 2.1 回滚商品信息
            SeckillGoods seckillGoods = (SeckillGoods) redisTemplate.boundHashOps("SeckillGoods_" + seckillStatus.getTime()).get(seckillStatus.getGoodsId());
            seckillGoods.setStockCount(seckillGoods.getStockCount() + 1);
            redisTemplate.boundHashOps("SeckillGoods_" + seckillStatus.getTime()).put(seckillStatus.getGoodsId(), seckillGoods);
            // 2.2 回滚商品的队列id
            redisTemplate.boundListOps("SeckillGoodsCountList_" + seckillStatus.getGoodsId()).leftPush(seckillStatus.getGoodsId());
            // 2.3 回滚库存
            //  redisTemplate.boundHashOps("SeckillGoodsCount").increment(seckillStatus.getGoodsId(), 1);


            // 3、删除排队信息、删除重复下单信息
            redisTemplate.boundHashOps("UserQueueStatus_" + user_id).delete(out_trade_no);
            redisTemplate.boundHashOps("UserQueueCount_" + user_id).delete(seckillOrder.getSeckillId());
        }
    }
}
